package in.muton.edushare.newentities;

import in.muton.edushare.EduShareSession;
import in.muton.edushare.processing.objects.CourseDataHandler;

import java.util.ArrayList;
import java.util.List;

import org.apache.wicket.model.IModel;

import com.edushare.common.dao.EnrolmentsDAO;
import com.edushare.common.orm.ORMInterface;
import com.edushare.common.vo.CourseInstances;
import com.edushare.common.vo.Enrolments;
import com.edushare.common.vo.UserDeptLink;
import com.edushare.common.vo.Users;

public class CourseUserCreator extends UserInviter {
	private static final long serialVersionUID = 1691533181831139507L;
	private IModel<CourseInstances> courseInstance;
	private ORMInterface ormInterface;
	private Integer userRole;
	
	public CourseUserCreator (ORMInterface ormInterface, IModel<CourseInstances> 
			courseInstance, Integer userRole) {
		super(ormInterface);
		this.courseInstance = courseInstance;
		this.userRole = userRole;
		this.ormInterface = ormInterface;
	}
	
	public List<String> addUsersToCourse(String fieldInput){
		String [] users = breakString(fieldInput);
		List<String> statusString = new ArrayList<String>();
		EnrolmentsDAO eDAO = new EnrolmentsDAO(ormInterface);
		DeptUserCreator duc = new DeptUserCreator(EduShareSession.get().getSessionORMInterface(),
				new CourseDataHandler(courseInstance).getOwner(),
				convertCourseRoleToDept(userRole));
		Users from = EduShareSession.get().getLoggedInUser();
		for(String u:users){
			Users userVO = getUserByString(u);
			if(userVO != null){
				statusString.add(eDAO.addUserFB(courseInstance.getObject(), userVO, userRole, from));
			}else{
				if(isEmailId(u)){
					duc.addUsersToDept(u);
					userVO = getUserByString(u);
					if(userVO != null){
						statusString.add(eDAO.addUserFB(courseInstance.getObject(), userVO, userRole, from));
					}else{
						statusString.add("Unable to invite user "+u+" due to unknown error.");
					}
				}else{
					statusString.add("Unable to determine the type of "+u);
				}
			}
		}
		return statusString;
	}
	
	public int convertCourseRoleToDept(int role){
		switch(role){
		case Enrolments.TEACHER:
			return UserDeptLink.TEACHER;
		case Enrolments.STUDENT:
		case Enrolments.TEACHING_ASSISTANT:
		case Enrolments.OBSERVER:
			return UserDeptLink.STUDENT;
		}
		return 0;
	}
	
}
